package cn.rongdao.jrkabao.ui.cashadvance;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.system.timer.FRTimer;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseLivenessActivity;
import cn.rongdao.jrkabao.bean.cashadvance.CashByCreditCardBean;
import cn.rongdao.jrkabao.bean.cashadvance.CashQuotaFullBean;
import cn.rongdao.jrkabao.bean.cashadvance.CreditAndDepositCardBean;
import cn.rongdao.jrkabao.bean.cashcoupon.GetCouponOkNumberBean;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.model.cashadvance.CashByCreditCardModel;
import cn.rongdao.jrkabao.model.cashadvance.CashQuotaFullModel;
import cn.rongdao.jrkabao.model.cashadvance.CreditModel;
import cn.rongdao.jrkabao.model.cashadvance.GetAllPassWayModel;
import cn.rongdao.jrkabao.model.cashadvance.SetDefaultCreditCardModel;
import cn.rongdao.jrkabao.model.cashcoupon.GetCouponOkNumberModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentifySuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.AddCreditCardForCashActivity;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.AddDepositCardActivity;
import cn.rongdao.jrkabao.ui.cashadvance.event.CashAdvanceSuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeCreditCardEvent;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeDepositCardEvent;
import cn.rongdao.jrkabao.ui.cashadvance.manager.CashAdvanceCardManager;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.CashBankCardUIComponent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.CashMoneyUIComponent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.ItemCashAdvanceSuccessUIComponent;
import cn.rongdao.jrkabao.ui.cashcoupon.SelectCashCouponActivity;
import cn.rongdao.jrkabao.ui.identify.ProgressValidateIdCardActivity;
import cn.rongdao.jrkabao.ui.webview.WebViewActivity;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.LoginUtil;
import cn.rongdao.jrkabao.util.growingio.BuriedUtil;
import cn.rongdao.jrkabao.widget.SelectCreditCardFromBottom;
import cn.rongdao.jrkabao.widget.SelectFeeFromBottom;

/**
 * Created by jack on 2017/6/2
 *
 * @author jack
 */

public class CashAdvanceActivity extends BaseLivenessActivity {

    public static final String INSTITUTION_ID = "institution_id";
    public static final String IS_FROM_ADD_CARD = "is_from_add_card";
    public static final String IS_FROM_SUCCESS = "is_from_success";

    public static void start(Context context, String institutionId, boolean isFromSuccess, boolean isFromAddCard) {
        Bundle bundle = new Bundle();
        bundle.putString(INSTITUTION_ID, institutionId);
        bundle.putBoolean(IS_FROM_SUCCESS, isFromSuccess);
        bundle.putBoolean(IS_FROM_ADD_CARD, isFromAddCard);
        FRStartActivity.start(context, CashAdvanceActivity.class, bundle);
    }

    public static void start(Context context, String institutionId) {
        start(context, institutionId, false, false);
    }

    public static void start(Context context, boolean isFromSuccess) {
        start(context, "", isFromSuccess, false);
    }

    public static void startFromAddCard(Context context) {
        start(context, "", false, true);
    }

    @BindView(R.id.aca_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.aca_ll_money)
    CashMoneyUIComponent cashMoneyUIComponent;
    @BindView(R.id.aca_tv_go_cash)
    TextView nextButtonUIComponent;
    @BindView(R.id.aca_cash_bank_card)
    CashBankCardUIComponent cashBankCardUIComponent;
    @BindView(R.id.acgp_cash_coupon)
    ItemCashAdvanceSuccessUIComponent mCashCoupon;

    private CashAdvanceCardManager cashAdvanceCardManager;
    private int isIdentify;
    private int isCredit;
    private int isBank;
    private int isPair;
    private int perCardMinLimit;
    private String institutionId;
    private String isJiFen;
    private List<CreditAndDepositCardBean> creditAndDepositCardBeanList;
    private int cashCouponPosition = -1;
    private String cashCouponMoney;
    private String cashCouponNum;
    private String cashCouponId;
    private FRTimer mTimer;
    private CashByCreditCardBean.PassWay passWay;
    private List<CashByCreditCardBean.PassWay> passWayList;

    private boolean isPayByH5;
    private String passWayId;

    @Override
    protected void initView() {
        super.initView();
        BuriedUtil.kamao_yemian_jiazaiwancheng_apply(thisActivity(), 1);
        cashMoneyUIComponent.setFocusa();
        cashAdvanceCardManager = new CashAdvanceCardManager(thisActivity());
        institutionId = getIntent().getStringExtra(INSTITUTION_ID);
        mCashCoupon.setContentNum("");
        initTitleBar();
        initData();
        initListener();
    }

    private void initListener() {
        nextButtonUIComponent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goCash();
            }
        });

        cashBankCardUIComponent.setOnCreditClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuriedUtil.kamao_quxian_anniu_apply(getActivity());
                if (LoginUtil.isLogin(thisActivity()) && isValidateIdCard(true)) {
                    if (!CommonUtil.isStatusSuccess(isCredit)) {
                        //实名但没绑信用卡，跳转到绑信用卡界面
                        AddCreditCardForCashActivity.start(thisActivity(), true, CommonUtil.isStatusSuccess(isBank), institutionId, false);
                    } else {
                        //弹窗
                        getCreditCardInfo();
                    }
                }
            }
        });

        cashBankCardUIComponent.setOnDepositClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.isLogin(thisActivity()) && isValidateIdCard(false)) {
                    if (!CommonUtil.isStatusSuccess(isBank)) {
                        //实名但没绑储蓄卡，跳转到绑储蓄卡界面
                        AddDepositCardActivity.start(thisActivity(), true, CommonUtil.isStatusSuccess(isCredit), institutionId, false);
                    }
                }
            }
        });

        cashAdvanceCardManager.setSelectCardDialogSelectedListener(new SelectCreditCardFromBottom.OnDialogSelectCardClickListener() {
            @Override
            public void onItemClick(int position) {
                if (CommonUtil.isStatusSuccess(creditAndDepositCardBeanList.get(position).getIs_default())) {
                    return;
                }
                cashAdvanceCardManager.dismiss();
                SetDefaultCreditCardModel.getInstance().executeCreditCard(creditAndDepositCardBeanList.get(position).getId(), new FRBaseObserver<String>(CashAdvanceActivity.this) {
                    @Override
                    protected void onBaseNext(String data) {
                        initPassWay();
                        initData();
                    }
                });
            }
        });

        cashAdvanceCardManager.setSelectFeeDialogSelectedListener(new SelectFeeFromBottom.OnDialogSelectCardClickListener() {
            @Override
            public void onItemClick(int position) {
                cashAdvanceCardManager.dismiss();
                passWay = passWayList.get(position);
                institutionId = passWay.getInstitution_id();
                passWayId = passWay.getId();
                isJiFen = passWay.getIs_jifen();
                cashMoneyUIComponent.setFeeContent(passWayList.get(position));
                setCouponButton();
                initData();
                getCashCoupon();
            }
        });

        cashAdvanceCardManager.setOnButterConfirmClickListener(new CashAdvanceCardManager.OnButterConfirmClickListener() {
            @Override
            public void onButtonConfirm() {
                confirmToPay();
            }
        });

        cashMoneyUIComponent.setChangeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFeeDialog();
            }
        });

        mCashCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginUtil.isLogin(thisActivity())) {
                    SelectCashCouponActivity.start(thisActivity(), cashMoneyUIComponent.getMoney(), cashCouponPosition,passWayId);
                }
            }
        });

        cashMoneyUIComponent.setOnMoneyInputListener(new CashMoneyUIComponent.OnMoneyInputListener() {
            @Override
            public void getMoney() {
                mTimer.schedule(1000, 500, 1, new Runnable() {
                    @Override
                    public void run() {
                        getCashCoupon();
                    }
                });
            }
        });
    }

    private void showFeeDialog() {
        GetAllPassWayModel.getInstance().execute(new FRBaseObserver<List<CashByCreditCardBean.PassWay>>(this) {
            @Override
            protected void onBaseNext(List<CashByCreditCardBean.PassWay> data) {
                passWayList = data;
                cashAdvanceCardManager.setSelectFeeAdapterList(data, passWay.getId(), cashMoneyUIComponent.getMoney());
            }
        });
    }

    private void getCreditCardInfo() {
        CreditModel.getInstance().execute(new FRBaseObserver<List<CreditAndDepositCardBean>>(this) {
            @Override
            protected void onBaseNext(List<CreditAndDepositCardBean> data) {
                creditAndDepositCardBeanList = data;
                cashAdvanceCardManager.setSelectCardAdapterList(data);
            }
        });
    }

    private void getCashCoupon() {
        if (!LoginUtil.isLogin()) {
            return;
        }
        if (FRString.isEmpty(cashMoneyUIComponent.getMoney())) {
            initCashCoupon("");
            return;
        }
        GetCouponOkNumberModel.getInstance().execute(passWayId,cashMoneyUIComponent.getMoney(), new FRBaseObserver<GetCouponOkNumberBean>(this) {
            @Override
            protected void onBaseNext(GetCouponOkNumberBean data) {
                cashCouponNum = data.getCoupon_use_number();
                initCashCoupon(cashCouponNum);
            }
        });
    }

    private void initCashCoupon(String cashCouponNum) {
        cashCouponId = "";
        cashCouponPosition = -1;
        mCashCoupon.setContentNum(cashCouponNum);
    }

    private void goCash() {
        if (LoginUtil.isLogin(thisActivity())) {
            if (!cashMoneyUIComponent.isMoneyCorrect()) {
                return;
            }
            if (!validateInfo()) {
                return;
            }
            if (Double.valueOf(cashMoneyUIComponent.getMoney()) < perCardMinLimit) {
                FRToast.showToastSafe("单笔订单最低额度不能低于" + perCardMinLimit);
                return;
            }
            goPay();
        }
    }

    private void goPay() {
        CashQuotaFullModel.getInstance().execute(passWayId, institutionId, isJiFen, cashMoneyUIComponent.getMoney(), new FRBaseObserver<CashQuotaFullBean>(this, "正在生成订单...") {
            @Override
            protected void onBaseNext(CashQuotaFullBean data) {
                if (CommonUtil.isStatusSuccess(data.getCode())) {
                    if (null != data.getConfirm() && !CommonUtil.isStatusSuccess(data.getConfirm().getCode())) {
                        cashAdvanceCardManager.showCashQuotaFullDialog(data, true);
                        return;
                    }
                    institutionId = data.getInstitution_id();
                    isPayByH5 = CommonUtil.isStatusSuccess(data.getType());
                    confirmToPay();
                } else {
                    cashAdvanceCardManager.showCashQuotaFullDialog(data, false);
                }
            }
        });
    }

    private void confirmToPay() {
        FRSharedPreferences.setStringDefault(SPConstant.CASH_ADVANCE_MONEY, cashMoneyUIComponent.getMoney());
        //实名且绑了两张卡
        if (null != passWay) {
            CashGoPayActivity.start(thisActivity(), isPayByH5, CommonUtil.isStatusSuccess(passWay.getIs_jifen()), cashCouponId, institutionId);
        } else {
            CashGoPayActivity.start(thisActivity(), isPayByH5, false, cashCouponId, institutionId);
        }
    }

    private boolean isValidateIdCard(boolean isCreditFirst) {
        if (!CommonUtil.isStatusSuccess(isIdentify)) {   //没实名
            ProgressValidateIdCardActivity.start(thisActivity(), institutionId, isCreditFirst, CommonUtil.isStatusSuccess(isPair));
            return false;
        }
        if (!CommonUtil.isStatusSuccess(isPair)) {  //没有进行活体
            setInstitutionId(institutionId);
            startLivenessActiviity(titleBarUIComponent);
            return false;
        }
        return true;
    }

    private boolean validateInfo() {
        if (isValidateIdCard(true)) {
            if (!CommonUtil.isStatusSuccess(isCredit) && !CommonUtil.isStatusSuccess(isBank)) {
                //实名但没绑卡，跳转到绑信用卡界面
                AddCreditCardForCashActivity.start(thisActivity(), true, false, institutionId, false);
                return false;
            }
            if (!CommonUtil.isStatusSuccess(isCredit) && CommonUtil.isStatusSuccess(isBank)) {
                //实名且绑了储蓄卡，跳转到绑信用卡界面
                AddCreditCardForCashActivity.start(thisActivity(), true, true, institutionId, false);
                return false;
            }
            if (CommonUtil.isStatusSuccess(isCredit) && !CommonUtil.isStatusSuccess(isBank)) {
                //实名且绑了信用卡，跳转到绑储蓄卡界面
                AddDepositCardActivity.start(thisActivity(), true, true, institutionId, false);
                return false;
            }
            return true;
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void changeCreditCardEventMessage(ChangeCreditCardEvent changeCreditCardEvent) {
        initPassWay();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void changeDepositCardEventMessage(ChangeDepositCardEvent changeDepositCardEvent) {
        initPassWay();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void cashAdvanceSuccessEventMessage(CashAdvanceSuccessEvent cashAdvanceSuccessEvent) {
        initPassWay();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void identifySuccessMessage(IdentifySuccessEvent identifySuccessEvent) {
        initPassWay();
    }

    private void initPassWay() {
        passWay = null;
        isJiFen = "";
        initData();
    }

    private void initData() {
        mTimer = new FRTimer();
        CashByCreditCardModel.getInstance().execute(FRString.valueOf(institutionId), isJiFen, new FRBaseObserver<CashByCreditCardBean>(this, "正在加载") {
            @Override
            protected void onBaseNext(CashByCreditCardBean data) {
                if (null != data) {
                    perCardMinLimit = data.getPerCardMinLimit();
                    isIdentify = data.getIs_identity();
                    isCredit = data.getIs_credit();
                    isBank = data.getIs_bank();
                    isPair = data.getIs_pair();
                    cashMoneyUIComponent.setTotalLeave(data.getSumAmount());
                    cashMoneyUIComponent.setPerCardLimit(data.getPerCardLimit());
                    cashMoneyUIComponent.setDayCardLimit(data.getDayCardLimit());
                    cashBankCardUIComponent.setCreditContent(data.getBank_name(), data.getBank_number(), data.getBank_icon());
                    cashBankCardUIComponent.setDepositContent(data.getDebit_bank_name(), data.getDebit_bank_number(), data.getDebit_bank_icon());
                    if (null == passWay) {
                        if (null != data.getPass_way()) {
                            passWay = data.getPass_way();
                            isJiFen = passWay.getIs_jifen();
                            institutionId = passWay.getInstitution_id();
                            passWayId = passWay.getId();
                            cashMoneyUIComponent.setFeeContent(data.getPass_way());
                            setCouponButton();
                            initCashCoupon("");
                        }
                    }
                    if (CommonUtil.isStatusSuccess(data.getRight_top_switch())) {
                        titleBarUIComponent.setRightVisible(true);
                    } else {
                        titleBarUIComponent.setRightVisible(false);
                    }
                }
            }
        });
        initLivenessDialog(titleBarUIComponent);
    }

    private void setCouponButton() {
        if (CommonUtil.isStatusSuccess(passWay.getCoupon_button())) {
            mCashCoupon.setVisibility(View.VISIBLE);
        } else {
            mCashCoupon.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SelectCashCouponActivity.REQUEST_CODE_SELECT_CASH_COUPON) {
            if (null != data) {
                cashCouponPosition = data.getIntExtra(SelectCashCouponActivity.CASH_COUPON_POSITION, -1);
                cashCouponMoney = data.getStringExtra(SelectCashCouponActivity.CASH_COUPON_MONEY);
                cashCouponId = data.getStringExtra(SelectCashCouponActivity.CASH_COUPON_ID);
            }
            if (FRString.isEmpty(cashCouponMoney)) {
                mCashCoupon.setContentNum(cashCouponNum);
            } else {
                mCashCoupon.setContentMoney(cashCouponMoney);
            }
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(IS_FROM_ADD_CARD, false)) {
            sendTaskCoupon();
        }
        if (intent.getBooleanExtra(IS_FROM_SUCCESS, false)) {
            //重置
            passWay = null;
            isJiFen = "";
            cashCouponId = "";
            cashCouponMoney = "";
            cashCouponNum = "";
            cashMoneyUIComponent.setMoney("");
            mCashCoupon.setContentNum("");
            initData();
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitle("信用卡取现");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBarUIComponent.setRightVisible(false);
        titleBarUIComponent.initRight(R.drawable.icon_question_mark, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.start(thisActivity(), InfoConstant.CASH_ADVANCE_EXPLAIN);
            }
        });
    }

    @Override
    protected boolean isNeedFinish() {
        return false;
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_cash_advance;
    }
}